package com.cilico.single.components;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.view.GestureDetector.OnGestureListener;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.cilico.single.R;
import com.cilico.single.utils.Utils;
import com.cilico.single.view.BaseView;
import com.cilico.single.view.FormLayout;
import com.cilico.single.waterfall.Waterfall;

public class mViewFlipper extends LinearLayout implements Component, OnGestureListener {
	Context context_ = null;
	private BaseView bv_;
	private ComponentListener listener_;
	List<ImageItem> imageItems;
	ViewFlipper flipper;
	boolean createOver_;
	public static Timer imgsTimer_ = null; // 图片滚动定时器
	TranslateAnimation translate;
	RelativeLayout.LayoutParams lyp;
	RelativeLayout parentLayout;
	TextView pageView; // 页数提示
	int xDown_;
	int xUp_;
	int yDown_;
	int yUp_;
	private long systemTime_ = 0;
	private long tempsystemTime_ = 0;
	private boolean isTouchUp_ = false;
	static Bitmap otherPageImg_ = null; // 当前页
	static Bitmap currentPageImg_ = null; // 其他页
	static int gridcount; // 图片的总页数
	static int currentPageIndex_ = 0; // 当前页索引
	
	ImageView hideOrShow;
	static Bitmap hideFlipperBitmap_; // 隐藏
	static Bitmap showFlipperBitmap_; // 显示
	public static final int eachCount = 2; // flipper一行显示图片数量
	static int page; // flipper总页数
	
	boolean isShrink_ = false; // 当点击hideOrShow按钮时为true
	int lastHeight_; // 上一次filpper底部距它父控件顶部的高度
	
	static final class TV extends TextView {

		public TV(Context context) {
			super(context);
			if (otherPageImg_ == null) {
				otherPageImg_ = BitmapFactory.decodeResource(this.getResources(), R.drawable.grayspot);

			}
			if (currentPageImg_ == null) {
				currentPageImg_ = BitmapFactory.decodeResource(this.getResources(), R.drawable.lightspot);
			}
		}

		protected void onDraw(Canvas canvas) {
			Paint paint_ = new Paint();
			int x;
			// 计算起画x坐标
			if ((page % 2) == 0) {
				x = Utils.screenWidth_ / 2 - (gridcount / 2) * 20 + 10;
			} else {
				x = Utils.screenWidth_ / 2 - (gridcount / 2) * 20;
			}
			for (int i = 0; i < page; i++) {
				if (currentPageIndex_ == i) {
					canvas.drawBitmap(currentPageImg_, x + 20 * i, 2, paint_);
				} else {
					canvas.drawBitmap(otherPageImg_, x + 20 * i, 2, paint_);
				}
			}
			super.onDraw(canvas);
		}

	}

	public mViewFlipper(Context context) {
		super(context);
		bv_ = (BaseView) context;
		createOver_ = true;
		setOrientation(LinearLayout.VERTICAL);
		setGravity(Gravity.CENTER_VERTICAL);
		bv_.runOnUiThread(new Runnable() {
			public void run() {
				flipper = new ViewFlipper(bv_);
				createOver_ = false;
			}
		});
	}

	public void initView() {
		currentPageIndex_ = 0;
		if (showFlipperBitmap_ == null) {
			showFlipperBitmap_ = BitmapFactory.decodeResource(this.getResources(), R.drawable.hidden_1);
		}
		if (hideFlipperBitmap_ == null) {
			Matrix mtx = new Matrix();  
			mtx.postRotate(180);  
			hideFlipperBitmap_ = Bitmap.createBitmap(showFlipperBitmap_, 0, 0, showFlipperBitmap_.getWidth(), showFlipperBitmap_.getHeight(), mtx, true);  
		}
		if (null == flipper) {
			bv_.runOnUiThread(new Runnable() {
				public void run() {
					flipper = new ViewFlipper(bv_);
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			});
		}
		if (flipper.getChildCount() <= 0) {
			// 显示隐藏
			hideOrShow = new ImageView(bv_);
			hideOrShow.setImageDrawable(new BitmapDrawable(hideFlipperBitmap_));
			hideOrShow.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
			hideOrShow.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					
					// 修正控件缩放，combobox没有回缩导致显示不正确的问题
					try {
						int size = bv_.vWidgetArray_.size();
						for (int i = 0; i < size; i++) {
							Object o = bv_.vWidgetArray_.elementAt(i);
							if (o instanceof ComboBox) {
								ComboBox combobox = (ComboBox)o;
								combobox.hide();
							}
						}
					} catch (Exception e) {
						Utils.printOutToConsole(e.getMessage());
					}
					bv_.runOnUiThread(new Runnable() {
						public void run() {
							if (parentLayout.getVisibility() == View.GONE) {
								hideOrShow.setImageDrawable(new BitmapDrawable(hideFlipperBitmap_));
								parentLayout.setVisibility(View.VISIBLE);
							} else if (parentLayout.getVisibility() == View.VISIBLE) {
								hideOrShow.setImageDrawable(new BitmapDrawable(showFlipperBitmap_));
								hideOrShow.setLayoutParams(new LinearLayout.LayoutParams(Utils.screenWidth_, LayoutParams.WRAP_CONTENT));
								parentLayout.setVisibility(View.GONE);
							}
							invalidate();
						}
					});
				}
			});
			
			// 父容器
			parentLayout = new RelativeLayout(bv_);
			parentLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
			lyp = new RelativeLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
			lyp.addRule(RelativeLayout.ALIGN_TOP);
			lyp.addRule(RelativeLayout.ALIGN_LEFT);
			
			// 图片集合
			flipper.setLayoutParams(lyp);
			flipper.setPadding(0, -5, 0, 0);
			
			if (gridcount > 0) {
				// 一个item显示n张，则flipper的子item总数为page
				page = gridcount / eachCount;
				// 奇数加1页
				if (gridcount % eachCount > 0) {
					page++;
				}
				for (int i = 0; i < page; i++) {
					// 初始化flipper子视图容器
					LinearLayout item = new LinearLayout(bv_);
					item.setLayoutParams(new LinearLayout.LayoutParams(-1, -2));
					item.setOrientation(LinearLayout.HORIZONTAL);
					
					// 按照一个item显示n张规则，为每一个item添加图片
					for (int k = 0; k< eachCount; k++) {
						int temId = i * eachCount + k;
						ImageItem img = null;
						try {
							img = imageItems.get(temId);
						} catch (Exception ex) {
							Utils.printOutToConsole(ex.getMessage());
						}
						if (null != img) {
							item.addView(imageItems.get(temId));
						}
					}
					
					// 最后一屏为奇数，则添加默认的图片
					if (gridcount % eachCount > 0) {
						Bitmap image = Utils.createImgWaitLoad(BaseView.mid_, "暂无图片", 0x88888888, Utils.screenWidth_ / mViewFlipper.eachCount, Utils.getSystemScaledValue(180));
						ImageItem tempItem_ = new ImageItem(bv_, image);
						tempItem_.setLayoutParams(new LinearLayout.LayoutParams(Utils.screenWidth_ / mViewFlipper.eachCount, Utils.getSystemScaledValue(180)));
						item.addView(tempItem_);
					}
					
					// 把item添加到父控件
					flipper.addView(item);
				}
				
			}

			// 页数提示
			pageView = new TV(bv_);
			flipper.setId(1);
			pageView.setGravity(Gravity.CENTER_HORIZONTAL);
			lyp = new RelativeLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, 10);
			lyp.addRule(RelativeLayout.ALIGN_BOTTOM, 1);
			pageView.setLayoutParams(lyp);
			pageView.setBackgroundColor(Color.GRAY);

			bv_.runOnUiThread(new Runnable() {
				public void run() {
					parentLayout.addView(flipper);
					parentLayout.addView(pageView);
					addView(hideOrShow);
					addView(parentLayout);
				}
			});

		}
		
		// 开启滚动
		if (gridcount > 1) {
			if (imgsTimer_ == null) {
				imgsTimer_ = new Timer();
			}
			imgsTimer_.schedule(new TimerTask() {
				public void run() {
					bv_.runOnUiThread(new Runnable() {
						public void run() {
							currentPageIndex_++;
							currentPageIndex_ = currentPageIndex_ % page;
							flipper.setInAnimation(AnimationUtils.loadAnimation(bv_, R.anim.push_left_in1));
							flipper.setOutAnimation(AnimationUtils.loadAnimation(bv_, R.anim.push_left_out1));
							flipper.showNext();
							pageView.invalidate();
						}
					});
				}
			}, 7000, 4000);
		}
	}

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		super.onLayout(changed, l, t, r, b);
		if (lastHeight_ != 0) {
			int margin = b - lastHeight_;
			if (isShrink_) {
//				shrinkWaterfall(margin);
			}
		}
		lastHeight_ = b;
		isShrink_ = false;
	}

	void shrinkWaterfall (int margin) {
		int size = bv_.vWidgetArray_.size();
		for (int i = 0; i < size; i++) {
			Object o = bv_.vWidgetArray_.elementAt(i);
			if (o instanceof Waterfall){
				Waterfall waterfall = (Waterfall) o;
//				waterfall.setMargin(margin);
//				waterfall.shrinkWidth();
//				waterfall.forceLayout();
//				ViewGroup.LayoutParams params = waterfall.getLayoutParams();  
//				params.height = 800;  
//				waterfall.setLayoutParams(params);
//				
//				waterfall.setCmpHeidht(800);
//				waterfall.refrshSelf();
			}
		}
	}
	
	void coverPressed(ImageItem clickItem) throws Exception {
		BaseView bv = (BaseView) this.getContext();
		if (listener_ != null) {
			listener_.componentAction(clickItem, bv);
		} else if (bv_ != null && bv_.listener_ != null) {
			bv_.listener_.componentAction(clickItem, bv);
		}
	}

	public boolean onTouchEvent(MotionEvent me) {
		// 取得触摸动作类型
		int action = me.getAction();
		switch (action) {

		case MotionEvent.ACTION_DOWN:
			xDown_ = (int) me.getX();
			yDown_ = (int) me.getY();
			systemTime_ = System.currentTimeMillis() - tempsystemTime_;
			tempsystemTime_ = System.currentTimeMillis();
			if (systemTime_ > 500 && yDown_ > 25) {// 操作过快
				isTouchUp_ = true;
			}
			break;

		case MotionEvent.ACTION_MOVE:
			// 注意不在此界面时（即发生页面跳转时）应取消定时器
			xUp_ = (int) me.getX();
			yUp_ = (int) me.getY();
			if (isTouchUp_) {
				if (Math.abs(xDown_ - xUp_) > 5) {
					if (xUp_ < xDown_) {
						currentPageIndex_++;
						currentPageIndex_ = currentPageIndex_ % page;
						flipper.setInAnimation(AnimationUtils.loadAnimation(bv_, R.anim.push_left_in1));
						flipper.setOutAnimation(AnimationUtils.loadAnimation(bv_, R.anim.push_left_out1));
						flipper.showNext();
						pageView.invalidate();
					} else {
						currentPageIndex_--;
						if (currentPageIndex_ < 0) {
							currentPageIndex_ = page + currentPageIndex_;
						}
						flipper.setInAnimation(AnimationUtils.loadAnimation(bv_, R.anim.push_right_in1));
						flipper.setOutAnimation(AnimationUtils.loadAnimation(bv_, R.anim.push_right_out1));
						flipper.showPrevious();
						pageView.invalidate();
					}
					isTouchUp_ = false;
				}
			}

			break;
		case MotionEvent.ACTION_UP:
			xUp_ = (int) me.getX();
			yUp_ = (int) me.getY();
			if (Math.abs(xDown_ - xUp_) <= 5 && Math.abs(yDown_ - yUp_) <= 5 && yDown_ > 25 && yUp_ > 25) {
				ImageItem clickItem_ = (ImageItem) imageItems.get(currentPageIndex_);
				if ((null != clickItem_) && (null != clickItem_.linkAddr_)) {
					try {
						if (imgsTimer_ != null) {
							imgsTimer_.cancel();
							imgsTimer_ = null;
						}
						coverPressed(clickItem_);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
			break;

		default:
			return super.onTouchEvent(me);
		}
		return true;
	}

	@Override
	public void cleanText() {
		// TODO Auto-generated method stub

	}

	@Override
	public String getContentText() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public CssStyle getCssStyle() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public FormLayout getForm() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int getCmpHeight() {
		// TODO Auto-generated method stub
		return this.getHeight();
	}

	@Override
	public View getCmpView() {
		// TODO Auto-generated method stub
		return this;
	}

	@Override
	public int getCmpWidth() {
		// TODO Auto-generated method stub
		return this.getWidth();
	}

	@Override
	public boolean isInTable() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void mould() {
		// TODO Auto-generated method stub

	}

	@Override
	public void releaseResource(View view) {
		// TODO Auto-generated method stub

	}

	@Override
	public void setContentText(String text) {
		// TODO Auto-generated method stub

	}

	@Override
	public void setCssStyle(CssStyle style) {
		// TODO Auto-generated method stub
		// cssStyle_ = style;
	}

	@Override
	public void setEncrypt(String encrypt) {
		// TODO Auto-generated method stub

	}

	@Override
	public void setForm(FormLayout formLayout) {
		// TODO Auto-generated method stub

	}

	@Override
	public void setInTable(boolean inTable) {
		// TODO Auto-generated method stub

	}

	@Override
	public void setCmpHeidht(int height) {
		// TODO Auto-generated method stub

	}

	@Override
	public void setCmpWidth(int width) {
		// TODO Auto-generated method stub

	}

	@Override
	public void shrinkWidth() {
		// TODO Auto-generated method stub

	}

	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {

		return false;
	}

	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		// TODO Auto-generated method stub
		return false;
	}

	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

}

